package com.cn.gxa.redis.service;

import com.cn.gxa.redis.bean.User;
import com.cn.gxa.redis.dao.UserDao;
import com.cn.gxa.util.JWTUtil;
import com.cn.gxa.util.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private RedisTemplate redisTemplate;

    public String login(String name, String password) {
        User user = userDao.findByUsernameAndPassword(name, password);
        String token = null;
        if (user != null) {
            //生成token
            token = JWTUtil.sign(user, 1000 * 60 * 30);
            //存入redis  设置有效时间
            //token= MD5Utils.md5(user.toString());
            redisTemplate.opsForValue().set(token, user);
        }

        return token;
        // key:eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2MjY4NTgyMDk3NzMsInBheWxvYWQiOiJ7XCJub1wiOjE4LFwidXNlcm5hbWVcIjpcIjFcIixcInBhc3N3b3JkXCI6XCIxXCIsXCJuaWNrXCI6bnVsbCxcImxvZ2ludGltZVwiOm51bGwsXCJhdXRoXCI6XCI3XCIsXCJiaXJ0aGRheVwiOm51bGx9In0.nVF8y789ZN83V-9pAaBKW6eH42lhfurVx7sI9y9BNAI
        //value  :对象
    }

    public List<User> findAll() {
        List<User> list = (List) redisTemplate.opsForValue().get("allUser");
        //在redis中没有
        if (list == null) {
            list = userDao.findAll();
            //存入redis中
            redisTemplate.opsForValue().set("allUser", list);
        }
        return list;
    }
}
